import React from 'react';
import { Form, Row, Col, Button,DatePicker } from 'antd';
import { withRouter } from 'react-router-dom';
import Grid from '../../components/table/grid';
import tranStartType from '../../utils/tranStartType';
import {sessionManager} from '../../utils/sessionStorage';
import { injectIntl } from 'react-intl';
import moment from 'moment';
import axios from 'axios';
const FormItem = Form.Item;
const createForm = Form.create;
const { RangePicker } = DatePicker;
@withRouter
class equChargeOrder extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            params: {
                qryType:0,
                chargeEndTimeStart:moment().subtract('days',31).format('YYYY.MM.DD 00:00:00'),
                chargeEndTimeEnd:moment().format('YYYY.MM.DD 23:59:00'),
                stubId:this.props.selectedInfo?this.props.selectedInfo.stubId:sessionManager.get('selectEquipment').id,
            },
            searchQuest:"",
            refresh:0,
            gridStyle:{
                scroll:true
            },
        };
        const common = this.props.intl.messages.common;
        this.columns = [
            {
                title: common.orderNO,
                dataIndex: 'id',
                key: 'id',
                width:250
            },
            {
                title: common.startTime,
                dataIndex: 'startTime',
                key: 'startTime',
                width:250
            },
            {
                title: common.endTime,
                dataIndex: 'endTime',
                key: 'endTime',
                width:250

            },
            {
                title: common.duration,
                dataIndex: 'chargeTime',
                key: 'chargeTime',
                width:150
            },
            {
                title: common.electricQuantity,
                dataIndex: 'electric',
                key: 'electric',
                width:150
            },
            {
                title: common.energyCharge,
                dataIndex: 'feeElectric',
                key: 'feeElectric',
                width:150
            },
            {
                title: common.serviceCharge,
                dataIndex: 'feeService',
                key: 'feeService',
                width:150
            },
            {
                title: common.chargingState,
                dataIndex: 'status',
                key: 'status',
                width:200
            },
            {
                title: common.startType,
                dataIndex: 'startType',
                key: 'startType',
                className:'SC-col-dots',
                width:200
            },
            {
                title: common.endInfo,
                dataIndex: 'endInfo',
                key: 'endInfo',
                className:'SC-col-dots',
                width:220,
                fixed: 'right',
            },
        ];
    }
    transformData=(data)=>{
        const common = this.props.intl.messages.common;
        data.forEach((item)=>{
            if(item.status===1){
                for(let key of Object.keys(item)){
                    if(key==="id"||key==="startTime"||key==="startType"){
                        item[key]=item[key]
                    }else if(key==="status"){
                        item.status="充电中"
                    }else if(key==="chargeTime"){
                        item.chargeTime=moment().diff(moment(item.startTime),'minutes')
                    }
                    else{
                        item[key]=""
                    }
                }
            }else{
                item.status=common.chargingCompleted;
            }
            item.startType=tranStartType(item.startType);
            return item
        });
        return data;
    };
    componentWillReceiveProps(nextProps) {
        if(nextProps.visible===true){
            this.setState({
                params:Object.assign(this.state.params,{stubId:nextProps.selectedInfo.stubId}),
                refresh:this.state.refresh+1,
            })
        }
    }
    // sendSword=()=> {
    //     this.refs.test.handleTableChange();
    // }

    obj2getParam=(values)=>{
        var params=``;
        for(let key of Object.keys(values)){
            if(typeof values[key]!=="undefined"){
                console.log(key,values[key]);
                params+=`${key}=${values[key]}&`
            }
        }
        this.setState({
            searchQuest:params
        })
    }
    //提交表格验证
    handleSubmit=(e)=>{
        e.preventDefault();
        this.props.form.validateFields((errors, values) => {
            if (errors) {
                console.log('Errors in form!!!');
                return;
            }
            console.log('Submit!!!',values);
            let chargeEndTimeStart=values.startTime[0].format('YYYY.MM.DD 00:00:00');
            let chargeEndTimeEnd=values.startTime[1].format('YYYY.MM.DD 23:59:00');
            let stubId=sessionManager.get('selectEquipment').id;
            let params={
                chargeEndTimeStart,
                chargeEndTimeEnd,
                stubId,
                qryType:0
            }
            this.obj2getParam(params)
            this.setState({
                params: {...params},
                refresh: this.state.refresh + 1
            });
        });
    }
    render(){
        let locale=sessionManager.get('locale');
        this.state.searchQuest=`qryType=${this.state.params.qryType}&chargeEndTimeStart=${this.state.params.chargeEndTimeStart?this.state.params.chargeEndTimeStart:''}&chargeEndTimeEnd=${this.state.params.chargeEndTimeEnd?this.state.params.chargeEndTimeEnd:''}&stubId=${this.state.params.stubId?this.state.params.stubId:''}&locale=${locale}`;
        const { getFieldDecorator } = this.props.form;
        const dateFormat = 'YYYY.MM.DD';
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
        };
        const common = this.props.intl.messages.common;
        const config = {
            rules: [{ type: 'array', required: true, message: '请选择时间!' }],
            // initialValue:moment(formDate.YMD(new Date()), dateFormat);
            initialValue:[moment(this.state.params.chargeEndTimeStart, dateFormat),moment(this.state.params.chargeEndTimeEnd, dateFormat)]
        };
        const token=(JSON.parse(sessionStorage.getItem("token"))||{}).token;
        return(
            <div>
                <form  form={this.props.form}>
                    <Row gutter={16}>
                        <Col xxl={5} xl={8}>
                            <FormItem
                                {...formItemLayout}
                                label={common.dateQuery}
                            >
                                {getFieldDecorator('startTime', config)(
                                    <RangePicker allowClear={false} format={dateFormat} placeholder="日期查询"/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={10}>
                            <FormItem>
                                <Button type="primary" icon="search" onClick={this.handleSubmit} style={{ marginRight: 8 }}>{common.search}</Button>
                                <a href={`${axios.defaults.baseURL}/api/order/list/export?${this.state.searchQuest}&token=${token}`}>
                                    <Button type="primary" className={'ant-btn-84'}>{common.exportStatement}</Button>
                                </a>
                            </FormItem>
                        </Col>
                    </Row>
                </form>
                <Grid transformData={this.transformData} refresh={this.state.refresh} params={this.state.params} columns={this.columns} url="api/order/list/qry" />
            </div>
        )
    }
}
equChargeOrder=createForm()(equChargeOrder);
export default injectIntl(equChargeOrder);